<template>
  <div>
    <!-- 广告系列表格展示开始 -->
    <el-card
      v-loading="tableLoading"
      class="box-card"
      :element-loading-text="tableLoadingtxt"
      shadow="never"
    >
      <div class="table-box">
        <cell-header title="广告系列" />
        <div v-show="!checkedList.length" class="table-choose-box flex">
          <ul class="set flex">
            <li>
              <span class="title"> 状态 </span>
              <div>
                <el-select
                  v-model="statusVal"
                  placeholder="请选择"
                  size="small"
                  @change="queryStatusChange"
                >
                  <template v-for="item in statusOP">
                    <el-option
                      v-if="!item.disabled"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </template>
                </el-select>
              </div>
            </li>

            <li>
              <span class="title"> 投放位置 </span>
              <div>
                <el-select
                  v-model="queryData.adChannelType"
                  placeholder="请选择"
                  size="small"
                  @change="queryDataChange"
                >
                  <el-option label="全部位置" :value="''" />
                  <el-option label="搜索结果" value="SEARCH" />
                  <el-option label="“搜索”标签" value="DISPLAY" />
                </el-select>
              </div>
            </li>
            <li>
              <div>
                <el-select
                  v-model="queryData.country"
                  placeholder="请选择"
                  size="small"
                  filterable
                  @change="queryDataChange"
                >
                  <el-option
                    v-for="item in addressOP"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  >
                    <p class="flex">
                      <country-flag :country="item.value" size="normal" />
                      {{ item.name }}
                    </p>
                  </el-option>
                </el-select>
              </div>
            </li>
            <li>
              <div>
                <el-input
                  v-model="queryData.name"
                  size="small"
                  placeholder="广告系列名称"
                  @keyup.enter.native="queryDataChange"
                >
                  <i
                    slot="suffix"
                    class="el-input__icon el-icon-search"
                    @click="queryDataChange"
                  />
                </el-input>
              </div>
            </li>
          </ul>
          <div />

          <div class="handle">
            <em @click="thShowChange">设置显示字段</em>
            <em @click="dowLoadCsv">导出数据</em>
          </div>
        </div>
        <table-batch-handle
          v-show="checkedList.length"
          :num="checkedList.length || 0"
          :del-show="false"
          @batchStart="handleBatchStart"
          @batchPause="handleBatchPause"
        />
        <div>
          <el-table
            ref="table"
            v-loading="tableLoading"
            :data="tableData"
            style="width: 100%"
            show-summary
            class="series-table"
            sortable="custom"
            :summary-method="returnTotal"
            :element-loading-text="tableLoadingtxt"
            :header-cell-class-name="headerStyle"
            :row-class-name="setRowClassName"
            @selection-change="tableCheckChange"
            @sort-change="tableSortChange"
          >
            <el-table-column
              v-if="typeSelectShow"
              type="selection"
              width="45"
              :selectable="
                (row, index) => {
                  return row.displayStatus !== 'DELETED';
                }
              "
            />
            <!-- 广告系列 -->
            <el-table-column
              label="广告系列"
              width="200"
              show-overflow-tooltip
              fixed="left"
            >
              <template slot-scope="scope">
                <div style="cursor: pointer" @click="goToSeriesInfo(scope.row)">
                  <el-image :src="scope.row.iconUrl" class="app-icon">
                    <div slot="error" class="image-slot">
                      <i class="iconfont icon-a-Vector1"></i>
                    </div>
                  </el-image>
                  <span
                    class="overflow-ellipsis"
                    style="display: inline-block; width: 80%"
                    >{{ scope.row.showName }}</span
                  >
                </div>
              </template>
            </el-table-column>
            <!-- 状态 -->
            <el-table-column label="状态" width="200" align="left">
              <template slot-scope="scope">
                <!-- 如果是删除了 -->
                <template v-if="scope.row.displayStatus == 'DELETED'">
                  <p
                    style="
                      display: flex;
                      align-items: center;
                      justify-content: flex-start;
                    "
                  >
                    <i class="del-color status-dot" /><span>已移除</span>
                  </p>
                </template>
                <!-- 否则 -->
                <template v-else>
                  <div>
                    <!-- 判断苹果状态 -->
                    <!-- 正在投放 -->
                    <p
                      v-if="scope.row.displayStatus === 'RUNNING'"
                      style="
                        display: flex;
                        align-items: center;
                        justify-content: flex-start;
                      "
                    >
                      <i class="liu-color status-dot" /><span>正在投放</span>
                    </p>

                    <!-- 已被用户暂停 -->
                    <p
                      v-else-if="
                        scope.row.displayStatus === 'PAUSED' &&
                        !scope.row.servingStateReasonsList
                      "
                      style="
                        display: flex;
                        align-items: center;
                        justify-content: flex-start;
                      "
                      class="pointer"
                    >
                      <i class="yellow-color status-dot" /> <span>已暂停</span>
                    </p>

                    <el-tooltip
                      v-else
                      class="item"
                      effect="dark"
                      placement="top"
                    >
                      <div slot="content">
                        <p
                          v-for="v in scope.row.servingStateReasonsList"
                          style="color: #fff !important"
                        >
                          {{ v }}
                        </p>
                      </div>
                      <p
                        style="
                          display: flex;
                          align-items: center;
                          justify-content: flex-start;
                        "
                        class="pointer"
                      >
                        <i class="yellow-color status-dot" />
                        <!-- <span
                          v-if="
                            scope.row.servingStateReasonsList &&
                            scope.row.servingStateReasonsList.length === 1
                          "
                          >{{ scope.row.servingStateReasonsList[0] }}</span
                        > -->
                        <span v-if="scope.row.displayStatus === 'ON_HOLD'"
                          >暂缓</span
                        >
                        <span v-else-if="scope.row.displayStatus === 'PAUSED'"
                          >已暂停</span
                        >
                        <span v-else>暂停</span>
                      </p>
                    </el-tooltip>
                  </div>
                </template>
              </template>
            </el-table-column>
            <el-table-column
              label="国家或地区"
              prop="name"
              width="160"
              align="left"
            >
              <template slot-scope="scope">
                <country-popover
                  v-if="scope.row.countryData.length > 1"
                  :country-data="scope.row.countryData"
                >
                  <p class="pointer" style="text-align: left">
                    多个国家地区({{ scope.row.countryData.length }})
                  </p>
                </country-popover>

                <div
                  v-else
                  class="flex"
                  style="
                    justify-content: flex-start;
                    width: 100%;
                    margin-left: -10px;
                  "
                >
                  <template v-for="(item, index) in scope.row.countryData">
                    <country-flag :country="item.value" size="normal" />
                    <span v-if="item">{{ item.name }}</span>
                  </template>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="投放位置" width="120" align="center">
              <template slot-scope="scope">
                {{
                  scope.row.adChannelType === "SEARCH"
                    ? "搜索结果"
                    : `“搜索”标签`
                }}
              </template>
            </el-table-column>

            <template v-for="(item, index) in thListCopy">
              <el-table-column
                v-if="item.show"
                :key="item.prop"
                :label="item.label"
                :prop="item.prop"
                :sortable="item.sort"
                :width="item.width || 120"
                :align="item.align || 'right'"
                class="right-box"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  <div v-if="item.prop === 'appName'">
                    <p
                      class="overflow-ellipsis"
                      style="width: 100%; cursor: default"
                    >
                      {{ scope.row.appName }}
                    </p>
                  </div>
                  <!-- 如果是每日预算 -->
                  <div
                    v-else-if="
                      item.showSta && scope.row.displayStatus !== 'DELETED'
                    "
                    :class="
                      item.label == '每日预算' && showStatus
                        ? 'price_div'
                        : 'price_no'
                    "
                    @click="openEdit(scope.row, item.label, scope.$index)"
                  >
                    <span
                      v-if="
                        item.pre &&
                        !(
                          item.label == '每日预算' &&
                          scope.$index === index_number
                        )
                      "
                    >
                      <span>{{ unitTxt }}</span>
                      <span>{{
                        scope.row.dailyBudgetAmount | $toFixed(2)
                      }}</span>
                    </span>
                    <el-input
                      v-if="
                        item.label == '每日预算' &&
                        scope.$index === index_number
                      "
                      v-model="scope.row[item.prop]"
                      v-focus
                      size="small"
                      @blur="editYS(scope.$index)"
                      @input="isChange"
                      @keyup.enter.native="editYS(scope.$index)"
                    ></el-input>
                    <span v-if="item.suf">{{ item.suf }}</span>
                  </div>
                  <!-- 生命周期预算 -->
                  <div v-else-if="item.prop === 'budgetAmount'">
                    <span v-if="scope.row.budgetAmount">{{
                      scope.row.budgetAmount | $toFixed(2)
                    }}</span>
                    <span v-else>-</span>
                  </div>
                  <!-- 则其他的是 -->
                  <div v-else>
                    <span v-if="item.pre">{{ unitTxt }}</span>
                    <span
                      v-if="
                        item.prop === 'taps' ||
                        item.prop === 'installs' ||
                        item.prop === 'impressions' ||
                        item.prop === 'campaignId' ||
                        item.prop === 'appName'
                      "
                      >{{ scope.row[item.prop] }}</span
                    >
                    <span v-else>{{ scope.row[item.prop] | $toFixed(2) }}</span>
                    <span v-if="item.suf">{{ item.suf }}</span>
                  </div>
                </template>
              </el-table-column>
            </template>
          </el-table>
          <div
            class="block"
            style="padding-top: 24px; display: flex; justify-content: flex-end"
          >
            <el-pagination
              :current-page="queryData.pageNum"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="10"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </el-card>

    <!-- 广告系列表格展示结束 -->
    <!-- 设置显示 -->
    <transfer-thead
      :default-th="thList"
      :th-list="thListCopy"
      :visible.sync="thVisible"
      @thListChange="handleSubThList"
    />
  </div>
</template>
<script>
import banner from "@/utils/world/banner.js";
import { findCountryByQuery } from "@/utils/index.js";
import { findMaxOne } from "@/api/create.js";
import {
  findReportCampaignList, // 表格数据
  findReportCampaignListTotal, // 总计数据
  downloadCampaignCsv, // 下载
  removeCampaign, // 删除
  modifyCampaign, // 修改广告系列组数据
} from "@/api/overView.js";

import { servingStateReasonscp } from "@/utils/servingStateReasons.js";
import countryPopover from "@/components/countryPopover/index.vue";
import tableBatchHandle from "../../components/table-batch-handle/index.vue";
import transferThead from "../../components/transferThead.vue";

export default {
  name: "", // ·������
  directives: {
    focus: {
      inserted: function (el) {
        el.querySelector("input").focus();
      },
    },
  },
  components: {
    tableBatchHandle,
    transferThead,
    countryPopover,
  },
  props: {},

  data() {
    return {
      tableTime: undefined,
      showStatus: true,
      isEdit: false,
      price: 0,
      index_number: "",
      checkedList: [], // 选择的表格数据
      addressOP: [
        {
          name: "全部国家",
          value: "",
        },
      ], // 国家地区数据选项；
      statusVal: "all",
      statusOP: [
        {
          // 状态选项
          label: "全部状态",
          value: "all",
        },
        {
          label: "正在投放",
          value: "RUNNING",
        },
        {
          label: "已暂停",
          value: "PAUSED",
        },
        {
          label: "暂缓",
          value: "ON_HOLD",
        },
        {
          label: "已移除",
          value: "DELETED",
        },
      ],
      /* 表格数据开启 */
      tableLoading: false,
      tableLoadingtxt: "数据加载中,请稍候",
      total: 0, // 总条数
      tableData: [], // 表格数据
      statisticalData: [], // 表格的总计数据
      queryData: {
        // 表格查询参数
        country: "",
        countrySX: this.$store.state.user.timeZone, // 时区
        timeZone: this.$store.getters.timeZoneTime,
        prop: "status", // 选择项
        order: "ascending", // 排序 /descending， ascending
        startTime: this.$store.state.overview.timeObj.overViewTime.startTime, // 开始时间
        endTime: this.$store.state.overview.timeObj.overViewTime.endTime, // 结束时间
        pageNum: 1, // 第多少页；
        pageSize: 10, // 每页多少条
        name: "", // 查询时的名称  模糊查询
        status: "",
        userId: this.$store.state.user.userInfo.userId,
        adChannelType: "", // 投放位置
        orgId: this.$route.query.orgId || "", // 如果是自助投放为空
        uuid: this.$route.query.uuid || "",
        aId: this.$route.query.aId || this.$route.query.aid || "",
        teamId: this.$store.state.team.teamId || "", // 团队
        campaignGroupId: this.$route.query.serialId || "",
        currencyType: this.$store.state.user.unit,
        state: "",
      },
      /* 表格数据结束 */
      /* 表头信息 */
      thVisible: false,
      thList: [
        {
          prop: "campaignId", // 属性
          label: "广告系列ID", // 名称
          align: "left",
          show: false, // 是否显示，
          sort: false, // 是否可以排序
          width: 150, // 宽度
        },
        {
          prop: "appName", // 属性
          label: "APP名称", // 名称
          align: "left",
          show: false, // 是否显示，
          sort: false, // 是否可以排序
          width: 200, // 宽度
        },
        {
          prop: "budgetAmount", // 属性
          label: "生命周期预算", // 名称
          show: true, // 是否显示，
          sort: true, // 是否可以排序
          width: 140, // 宽度
          pre: "$",
        },
        {
          prop: "dailyBudgetAmount", // 属性
          label: "每日预算", // 名称
          show: true, // 是否显示，
          sort: true, // 是否可以排序
          showSta: true, // 是否点击
          width: 160,
          pre: "$",
        },
        {
          prop: "localSpendAmount", // 属性
          label: "花费", // 名称
          show: true, // 是否显示，
          sort: true, // 是否可以排序
          pre: "$",
        },

        {
          prop: "impressions", // 属性
          label: "展示", // 名称
          show: true, // 是否显示，
          sort: true, // 是否可以排序
        },
        {
          prop: "taps", // 属性
          label: "点击", // 名称
          show: true, // 是否显示，
          sort: true, // 是否可以排序
        },
        {
          prop: "installs", // 属性
          label: "安装", // 名称
          show: true, // 是否显示，
          sort: true, // 是否可以排序
        },
        {
          prop: "avgCpaAmount", // 属性
          label: "平均CPA", // 名称
          show: true, // 是否显示，
          sort: true, // 是否可以排序
          pre: "$",
        },
        {
          prop: "avgCptAmount", // 属性
          label: "平均CPT", // 名称
          show: true, // 是否显示，
          sort: true, // 是否可以排序
          pre: "$",
        },
        {
          prop: "avgCpmAmount", // 属性
          label: "平均CPM", // 名称
          show: true, // 是否显示，
          sort: true, // 是否可以排序
          pre: "$",
        },

        {
          prop: "ttr", // 属性
          label: "点击率", // 名称
          show: true, // 是否显示，
          sort: true, // 是否可以排序
          suf: "%",
        },
        {
          prop: "conversionRate", // 属性
          label: "转化率", // 名称
          show: true, // 是否显示，
          sort: true, // 是否可以排序
          suf: "%",
        },
        {
          prop: "newDownloads", // 属性
          label: "新增下载", // 名称
          show: false, // 是否显示，
          sort: true, // 是否可以排序
        },
        {
          prop: "redownloads", // 属性
          label: "重复下载", // 名称
          show: false, // 是否显示，
          sort: true, // 是否可以排序
        },
        {
          prop: "latOffinstalls", // 属性
          label: "关闭LAT下载", // 名称
          show: false, // 是否显示，
          sort: true, // 是否可以排序
          width: 200, // 宽度
        },
        {
          prop: "latOninstalls", // 属性
          label: "开启LAT下载", // 名称
          show: false, // 是否显示，
          sort: true, // 是否可以排序
          width: 200, // 宽度
        },
      ],
      thListCopy: [],
    };
  },

  computed: {
    // 选择的时间
    timeArr() {
      return this.$store.state.overview.timeObj.overViewTime;
    },
    // 选择的时区
    timeZone() {
      return this.$store.state.user.timeZone;
    },

    unitTxt() {
      const unit = this.$store.state.user.unit;
      this.$forceUpdate();
      return unit === "RMB" ? "￥" : "$";
    },
    // 数据概览页面  表格是否可以多选
    typeSelectShow() {
      if (
        this.$route.query.uuid &&
        (this.$route.query.orgId || this.$route.query.orgid)
      ) {
        const index = this.$store.state.overview.allAc.findIndex((item) => {
          return item.uuid === this.$route.query.uuid;
        });

        const i = this.$store.state.overview.allAc[index].org.findIndex(
          (item) => {
            return (
              item.orgId === this.$route.query.orgId * 1 ||
              item.orgId === this.$route.query.orgid * 1
            );
          }
        );
        if (
          this.$store.state.overview.allAc[index].roleName ===
            "invalid_client" ||
          this.$store.state.overview.allAc[index].roleName === "API Read Only"
        ) {
          return false;
        }

        const orgRole = this.$store.state.overview.allAc[index].org[i].roleName;

        return (
          orgRole !== "API Read Only" &&
          !this.$isReadOnly(this.$store.state.user.userInfo.roleName)
        );
      } else {
        return !this.$isReadOnly(this.$store.state.user.userInfo.roleName);
      }
    },
  },
  watch: {
    $route: {
      deep: true,
      handler: function (newV, oldV) {
        if (this.tableTime) {
          clearTimeout(this.tableTime);
        }
        if (this.$route.query.uuid) {
          this.tableTime = setTimeout(() => {
            this.$nextTick(() => {
              this.queryData.pageNum = 1;
              this.findReportCampaignListTotal();
              this.findReportCampaignList();
            });
          }, 300);
        }
      },
    },
    timeArr: {
      // �����Ķ���
      deep: true,
      handler: function (newV, oldV) {
        this.queryData.startTime = newV.startTime;
        this.queryData.endTime = newV.endTime;
        this.queryData.pageNum = 1;
        this.findReportCampaignListTotal();
        this.findReportCampaignList();
      },
    },
    timeZone: {
      deep: true,
      handler: function (newV, oldV) {
        this.queryData.countrySX = this.$store.state.user.timeZone; // 时区
        this.queryData.timeZone = this.$store.getters.timeZoneTime;
        this.queryData.pageNum = 1;
        this.findReportCampaignListTotal();
        this.findReportCampaignList();
      },
    },
    tableData(newV) {
      this.tableData = newV;
    },
  },
  // ������
  // created() {
  //   // 创建国家地区选择项
  //   const arr = banner.zhCN.map((item) => {
  //     const index = item.icon.lastIndexOf("-");
  //     const str = item.icon.slice(index + 1).toUpperCase();
  //     item.value = str === "UK" ? "GB" : str;
  //     return item;
  //   });
  //   this.addressOP.push(...arr);
  // },
  // ���غ�
  mounted() {
    if (localStorage.getItem("series-DATA-Thlist")) {
      this.thListCopy = JSON.parse(localStorage.getItem("series-DATA-Thlist"));
    } else {
      this.thListCopy = JSON.parse(JSON.stringify(this.thList)); // 默认的显示字段
    }
    if (this.$route.query.uuid) {
      this.findReportCampaignListTotal();
      this.findReportCampaignList();
    }
  },
  // ���ٺ�
  beforeDestroy() {
    if (this.tableTime) return clearTimeout(this.tableTime);
  },

  // ����
  methods: {
    setRowClassName(data) {
      if (data.row.displayStatus === "DELETED") {
        console.log("进入这里了吗");
        return "del-row";
      } else {
        return "";
      }
    },
    headerStyle({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 2 && this.typeSelectShow) {
        return "center-align";
      }
    },
    // 是否改变数据
    isChange(value) {
      if (value) {
        this.isEdit = true;
      }
    },
    // 获取每日最低预算
    async findMaxOne() {
      const obj = {
        orgId: this.$route.query.orgId || "", // 如果是自助投放为空
        uuid: this.$route.query.uuid || "",
        aId: this.$route.query.aId || this.$route.query.aid || "",
        campaignId: this.tableData[this.index_number].campaignId,
        currencyType: this.$store.state.user.unit,
        teamId: this.$store.state.team.teamId,
      };
      const res = await findMaxOne(obj);
      this.price = res.data.data * 1;
    },
    editYS(index) {
      this.showStatus = true;
      if (!this.isEdit) {
        this.index_number = -1;
      } else if (this.tableData[index].dailyBudgetAmount * 100 < 1) {
        this.$message.error("你的每日预算上限必须至少为0.01");
        this.findReportCampaignList();
        this.index_number = -1;
        this.isEdit = false;
      } else if (this.tableData[index].budgetAmount) {
        if (
          this.tableData[index].dailyBudgetAmount * 1 >
            this.tableData[index].budgetAmount * 1 ||
          this.tableData[index].dailyBudgetAmount * 100 < 1
        ) {
          this.$message.error(
            "你的每日预算上限必须至少为0.01 且不得超过广告系列预算"
          );
          this.findReportCampaignList();
          this.index_number = -1;
          this.isEdit = false;
        }
      } else if (this.price * 1 > this.tableData[index].dailyBudgetAmount * 1) {
        this.$message.error(
          "每日预算不能低于该广告系列的关键词/单次点击费用最高价"
        );
        this.findReportCampaignList();
        this.index_number = -1;
        this.isEdit = false;
      } else {
        const arr = [];
        arr.push({
          teamId: this.$store.state.team.teamId,
          currencyType: this.$store.state.user.unit,
          campaignGroupId: this.tableData[index].campaignGroupId,
          campaignId: this.tableData[index].campaignId,
          userId: this.$store.state.user.userInfo.userId,
          orgId: this.$route.query.orgId || "", // 如果是自助投放为空
          uuid: this.$route.query.uuid || "",
          aId: this.$route.query.aId || this.$route.query.aid || "",
          updateCampaign: {
            campaign: {
              dailyBudgetAmountNub: this.tableData[index].dailyBudgetAmount, // 属性
            },
          },
        });
        this.modifyCampaign(arr);
      }
    },
    // 打开编辑框
    openEdit(data, name, index) {
      this.index_number = index;
      if (name === "每日预算") {
        if (data.adChannelType === "SEARCH") {
          this.findMaxOne();
        } else {
          this.price = 0;
        }
        this.tableData.forEach((item, i) => {
          if (index === i) {
            this.showStatus = false;
          }
        });
      }
    },
    // 查询广告系列组 总计数据查询
    async findReportCampaignListTotal() {
      const obj = {
        ...this.queryData,
        orgId: this.$route.query.orgId || "", // 如果是自助投放为空
        uuid: this.$route.query.uuid || "",
        aId: this.$route.query.aId || this.$route.query.aid || "",
        currencyType: this.$store.state.user.unit,
        teamId: this.$store.state.team.teamId || "", // 团队
        campaignGroupId: this.$route.query.serialId || "",
      };

      const res = await findReportCampaignListTotal(obj);
      if (res.data.code === 20000) {
        this.statisticalData = res.data.data;
      } else {
        this.$message.closeAll();
        this.$message.error(
          res.data.message || "表格总计数据获取失败，请稍后重试"
        );
      }
    },

    queryStatusChange(val) {
      if (val === "all") {
        this.queryData.status = "";
        this.queryData.state = undefined;
      } else if (val === 0) {
        this.queryData.status = "";
        this.queryData.state = "0";
      } else {
        this.queryData.status = val;
        this.queryData.state = undefined;
      }

      this.queryData.pageNum = 1;
      this.findReportCampaignList();
      this.findReportCampaignListTotal(); // 查询总计数据
    },

    // 查询广告系列组 表格数据
    async findReportCampaignList() {
      this.tableLoading = true;
      this.$forceUpdate();
      this.tableLoadingtxt = "数据获取中，请稍候";
      const obj = {
        ...this.queryData,
        orgId: this.$route.query.orgId || "", // 如果是自助投放为空
        uuid: this.$route.query.uuid || "",
        aId: this.$route.query.aId || this.$route.query.aid || "",
        currencyType: this.$store.state.user.unit,
        teamId: this.$store.state.team.teamId || "", // 团队
        campaignGroupId: this.$route.query.serialId || "",
      };

      const res = await findReportCampaignList(obj);
      this.tableLoading = false;

      if (res.data.code === 20000) {
        const { data } = res.data;
        this.total = data.total;

        // 处理数据
        const arr = data.list.map((item) => {
          var showName = undefined;

          // 处理名称；
          if (
            !this.$route.query.modelType ||
            this.$route.query.modelType === "self-help"
          ) {
            const index = item.name.indexOf("_3YData_");
            showName = item.name.slice(index + 8); // 将campian名称前缀去掉
          } else {
            showName = item.name;
          }
          // 处理可搜索的国家
          this.addressOP = [
            {
              name: "全部国家",
              value: "",
            },
          ];
          let countriesOrRegionStr = JSON.parse(
            JSON.stringify(data.list[0].countriesOrRegionStr)
          );
          let country = countriesOrRegionStr.substring(
            1,
            countriesOrRegionStr.length - 1
          );
          country = country.replace(/\s*/g, "");
          let contry2 = country.split(",");
          banner.zhCN.forEach((item) => {
            contry2.forEach((index) => {
              const indexs = item.icon.lastIndexOf("-");
              const str = item.icon.slice(indexs + 1).toUpperCase();
              item.value = str === "UK" ? "GB" : str;
              if (item.value == index) {
                this.addressOP.push(item);
              }
            });
          });
          // 处理国家
          const countryData = findCountryByQuery(item.countriesOrRegions, true);
          // 处理状态值
          let servingStateReasons = JSON.parse(
            JSON.stringify(item.servingStateReasons)
          );
          if (servingStateReasons) {
            item.servingStateReasonsList= servingStateReasonscp(servingStateReasons);
          } else {
            item.servingStateReasonsList = "";
          }
          return { ...item, showName, countryData };
        });
        this.$nextTick(() => {
          this.tableData = arr.map((item) => {
            item.localSpendAmount = item.localSpendAmount * 1;
            item.avgCpaAmount = item.avgCpaAmount * 1;
            item.avgCptAmount = item.avgCptAmount * 1;
            item.budgetAmount = item.budgetAmount * 1;
            item.ratingCount = item.ratingCount * 1;
            item.userRating = item.userRating * 1;
            if (
              item.avgCpmAmount &&
              item.avgCpmAmount !== null &&
              item.avgCpmAmount !== undefined
            ) {
              item.avgCpmAmount = item.avgCpmAmount * 1;
            }
            if (
              item.dailyBudgetAmount &&
              item.dailyBudgetAmount !== null &&
              item.dailyBudgetAmount !== undefined
            ) {
              item.dailyBudgetAmount = item.dailyBudgetAmount * 1;
            }
            return item;
          });
          // this.$refs.table.doLayout()
        });
      } else {
        this.$message.closeAll();
        this.$message.error(
          res.data.message || "广告系列组数据获取失败，请稍后重试"
        );
      }
    },
    // 设置显示字段的弹窗显示
    thShowChange() {
      this.thVisible = true;
    },

    handleSubThList(arr) {
      this.thListCopy = JSON.parse(JSON.stringify(arr));
      localStorage.setItem("series-DATA-Thlist", JSON.stringify(arr));
      this.$refs["table"].doLayout();
      this.$forceUpdate();
    },

    // 对远程获取到的统计数据做出处理
    returnTotal(param) {
      const { columns, data } = param;

      const sums = [];
      columns.forEach((column, index) => {
        if (index === 2) {
          sums[index] = "总计";
          return;
        } else if (index === 3) {
          sums[index] = "";
        } else {
          for (const key in this.statisticalData[0]) {
            if (key === column.property) {
              switch (key) {
                case "appName":
                  sums[index] = "";
                  break;
                case "campaignId":
                  sums[index] = "";
                  break;
                case "budgetAmount":
                  sums[index] = "";
                  break;
                case "dailyBudgetAmount":
                  sums[index] = "";
                  break;
                case "localSpendAmount":
                  sums[index] =
                    this.unitTxt +
                    (this.statisticalData[0][key] * 1).toFixed(2);
                  break;
                case "avgCpaAmount":
                  sums[index] =
                    this.unitTxt +
                    (this.statisticalData[0][key] * 1).toFixed(2);
                  break;
                case "avgCptAmount":
                  sums[index] =
                    this.unitTxt +
                    (this.statisticalData[0][key] * 1).toFixed(2);
                  break;
                case "ttr":
                  sums[index] =
                    (this.statisticalData[0][key] * 1).toFixed(2) + "%";
                  break;
                case "conversionRate":
                  sums[index] =
                    (this.statisticalData[0][key] * 1).toFixed(2) + "%";
                  break;
                case "impressions":
                  sums[index] = this.statisticalData[0][key] * 1;
                  break;
                case "taps":
                  sums[index] = this.statisticalData[0][key] * 1;
                  break;
                case "installs":
                  sums[index] = this.statisticalData[0][key] * 1;
                  break;

                default:
                  sums[index] = (this.statisticalData[0][key] * 1).toFixed(2);
                  break;
              }
            }
          }
        }
      });

      return sums;
    },

    // 表格勾选参数
    tableCheckChange(data) {
      this.checkedList = JSON.parse(JSON.stringify(data));
    },

    // 对表格的批量操作
    handleBatchStart() {
      // 批量开启
      // 待支付的广告系列将无法开启
      this.tableLoading = true;
      this.tableLoadingtxt = "数据开启中,请稍候";
      const arr = [];
      let falg = true;
      this.checkedList.forEach((item) => {
        if (
          item.orderState * 1 === 0 ||
          item.orderState === null ||
          item.orderState === undefined
        ) {
          falg = false;
        } else {
          arr.push({
            teamId: this.$store.state.team.teamId || "",
            currencyType: this.$store.state.user.unit,
            campaignId: item.campaignId,
            campaignGroupId: item.campaignGroupId,
            userId: this.$store.state.user.userInfo.userId,
            uuid: this.$route.query.uuid || "", // 自助投放为空
            orgId: this.$route.query.orgId || "", // 自助投放为空
            aId: this.$route.query.aId || this.$route.query.aid || "",
            updateCampaign: {
              campaign: {
                status: "ENABLED",
              },
            },
          });
        }
      });
      if (!falg) {
        this.$message.closeAll();
        this.$message.error("待支付的广告系列将无法开启");
      }
      if (arr.length) {
        this.modifyCampaign(arr);
      } else {
        this.tableLoading = false;
      }
    },
    handleBatchPause() {
      this.tableLoading = true;
      this.tableLoadingtxt = "数据暂停中,请稍候";
      // 批量暂停
      const arr = [];
      this.checkedList.forEach((item) => {
        arr.push({
          teamId: this.$store.state.team.teamId || "",
          currencyType: this.$store.state.user.unit,
          campaignId: item.campaignId,
          campaignGroupId: item.campaignGroupId,
          userId: this.$store.state.user.userInfo.userId,
          orgId: this.$route.query.orgId || "", // 如果是自助投放为空
          uuid: this.$route.query.uuid || "",
          aId: this.$route.query.aId || this.$route.query.aid || "",
          updateCampaign: {
            campaign: {
              status: "PAUSED",
            },
          },
        });
      });
      this.modifyCampaign(arr);
    },

    async modifyCampaign(arr) {
      const res = await modifyCampaign(arr);
      this.index_number = -1;
      this.isEdit = false;
      if (res.data.code && res.data.code === 20000) {
        this.tableLoading = true;
        this.tableLoadingtxt = "数据更新中,请稍候";
        setTimeout(() => {
          this.findReportCampaignList();
          this.findReportCampaignListTotal();
        }, 2000);
      } else {
        this.$message.closeAll();
        this.$message.error(res.data.message || "服务器错误，请稍后重试");
      }
    },

    /*    handleBatchDel() {
                  this.$confirm('一旦移除便无法恢复或修改，历史记录报告仍可查看。冻结余额需5-10个工作日后解冻', '警告！移除广告系列数据永久性操作?', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'

                  }).then(async() => {
                    const arr = this.checkedList.map(item => {
                      const obj = {
                        teamId: this.$store.state.team.teamId || '',
                        orgId: this.$route.query.orgId ? this.$route.query.orgId.toString() : '', // 如果是自助投放为空
                        uuid: this.$route.query.uuid || '',
                        aId: this.$route.query.aId || this.$route.query.aid || '',
                        campaignId: item.campaignId,
                        campaignGroupId: item.campaignGroupId,
                        currencyType: this.$store.state.user.unit
                      }
                      return obj
                    })

                    const res = await removeCampaign(arr)

                    if (res.data.code === 20000) {
                      this.checkedList = []
                      this.queryData.pageNum = 1
                      this.findReportCampaignList()
                      this.findReportCampaignListTotal()
                      this.$store.dispatch('overview/getAllCampaign', {
                        teamId: this.$store.state.team.teamId || '',
                        orgId: this.queryData.orgId,
                        uuid: this.queryData.uuid,
                        aId: this.$route.query.aId || this.$route.query.aid || '',
                        appid: '',
                        currencyType: this.queryData.currencyType,
                        campaignGroupId: this.$route.query.serialId || 0
                      })
                      this.$message.closeAll()
                      this.$message({
                        message: res.data.message || '操作成功，正在刷新数据',
                        type: 'success'
                      })
                    } else {
                      this.$message.closeAll()
                      this.$message.error(res.data.message || '服务器出现错误')
                    }
                  })
                }, */

    // 去广告系列详情
    goToSeriesInfo(row) {
      this.$router.push({
        name: "seriesOverview",
        query: {
          ...this.$route.query,
          modelType: this.$route.query.modelType || "self-help",
          campaignId: row.campaignId,
          serialId: row.campaignGroupId,
          caStatus: row.displayStatus,
        },
      });
    },

    // 下载表格数据
    async dowLoadCsv() {
      if (!this.tableData.length) {
        this.$message.closeAll();
        this.$message.error("请先创建广告系列");
        return false;
      }

      const res = await downloadCampaignCsv({
        ...this.queryData,
        pageNum: 1,
        pageSize: this.total,
        teamId: this.$store.state.team.teamId || "",
        orgId: this.queryData.orgId,
        uuid: this.queryData.uuid,
        aId: this.$route.query.aId || this.$route.query.aid || "",
        appid: "",
        currencyType: this.queryData.currencyType,
        campaignGroupId: this.$route.query.serialId || 0,
      });
      if (!res.data.message) {
        const blob = new Blob(["\ufeff" + res.data], {
          type: "text/csv,charset=UTF-8",
        });
        const that = this;
        const objectUrl = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.setAttribute("href", objectUrl);
        a.setAttribute(
          "download",
          "YYY_DATA_竞价计划列表_" +
            that.queryData.startTime +
            "_" +
            this.queryData.endTime +
            ".csv"
        );
        a.click();
      } else {
        this.$message.closeAll();
        this.$message.error(res.data.message || "导出数据失败，请稍后重试");
      }
    },
    // 搜索选择等发生了变化
    queryDataChange() {
      this.queryData.pageNum = 1;
      this.findReportCampaignList();
      this.findReportCampaignListTotal(); // 查询总计数据
    },

    ryStatusChange(val) {
      if (val === "all") {
        this.queryData.status = "";
        this.queryData.state = "";
      } else if (val === 0) {
        this.queryData.status = "";
        this.queryData.state = "0";
      } else {
        this.queryData.status = val;
        this.queryData.state = "";
      }
      this.queryData.pageNum = 1;
      this.findReportCampaignList();
      this.findReportCampaignListTotal(); // 查询总计数据
    },

    // 排序变化
    tableSortChange(obj) {
      if (!obj.order) {
        this.queryData.prop = "status";
        this.queryData.order = "descending";
      } else {
        this.queryData.prop = obj.prop;
        this.queryData.order = obj.order;
      }
      this.queryData.pageNum = 1;
      this.findReportCampaignList();
      this.findReportCampaignListTotal(); // 查询总计数据
    },

    // 每页多少条
    handleSizeChange(index) {
      this.queryData.pageSize = index;
      this.findReportCampaignList();
      this.findReportCampaignListTotal(); // 查询总计数据
    },
    // 页数
    handleCurrentChange(index) {
      this.queryData.pageNum = index;
      this.findReportCampaignList();
      this.findReportCampaignListTotal(); // 查询总计数据
    },
  },
};
</script>

<style lang="scss" scoped="true">
@import "~@/styles/variables.scss";

.data {
  padding-bottom: 24px;
}

.trend-card {
  margin-bottom: 24px;
}

.table-box {
  .series-table {
    margin-top: 24px;

    /deep/ thead {
      th.el-table__cell.is-right > .cell {
        padding-left: 10px !important;
        padding-right: 24px;

        .caret-wrapper {
          position: absolute;
          top: 50%;
          right: 0;
          transform: translateY(-46%);
        }
      }
    }

    /deep/ .app-icon {
      height: 24px;
      width: 24px;
      border-radius: 2px;
      margin-right: 12px;

      i {
        font-size: 22px;
        color: #acb6c2;
      }
    }

    /deep/ .el-table__body {
      background: #ffffff;

      .el-table__cell.is-right > .cell {
        padding-right: 24px;
      }
    }

    /deep/ .el-table__footer-wrapper .el-table__cell.is-right > .cell {
      padding-right: 24px;
    }

    /deep/ .del-row {
      background: rgba(57, 68, 78, 0.1);

      td,
      .cell {
        background: transparent !important;
      }
    }
  }
}

.price_div {
  border: 1px solid transparent;
  padding: 2px;
  border-radius: 2px;
}

.price_div:hover {
  border: 1px solid #e0e2e7;
  border-radius: 2px;
}

@import "../../components/handle.scss";
</style>
